package b1.mobile.blackberry.screen;

import org.json.me.JSONArray;
import org.json.me.JSONObject;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.ButtonFieldFactory;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.DialogClosedListener;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.DialogFieldManager;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.BackgroundFactory;
import b1.mobile.blackberry.controller.AgentController;
import b1.mobile.blackberry.entity.ApprovalInfo;
import b1.mobile.blackberry.io.http.ResponseParserHelper;
import b1.mobile.blackberry.io.http.Serviceworker;
import b1.mobile.blackberry.io.http.Serviceworker.ServiceDelegate;
import b1.mobile.blackberry.io.http.SoapContentProvider;
import b1.mobile.blackberry.ui.component.ImageButton;
import b1.mobile.blackberry.ui.component.ListGroupItemField;
import b1.mobile.blackberry.ui.component.ListGroupItemManager;
import b1.mobile.blackberry.ui.component.SAPTitleBar;
import b1.mobile.blackberry.ui.component.SingleLineEditField;
import b1.mobile.blackberry.ui.component.util.FieldFactory;
import b1.mobile.blackberry.ui.component.util.FontFactory;
import b1.mobile.blackberry.ui.component.util.ThemeUtil;
import b1.mobile.blackberry.util.JSONUtil;

public class ApprovalDetailScreen extends BaseFunctionScreen implements ServiceDelegate, DialogClosedListener{

	private Manager manager;
	
	String _id;
	private JSONObject result;
	
	Dialog _approveDialog;
	Dialog _rejectDialog;
	
	SingleLineEditField _approveRemark;
	SingleLineEditField _rejectRemark;

	public ApprovalDetailScreen(String approvalId) {
		
		setTitle(FieldFactory.makeScreenTitle("Approval Detail"));
		ThemeUtil.decorateScreen(this);
		
		manager = new ListGroupItemManager();
		this.add(manager);
				
		_id = approvalId;

	}
	
	/*
	 * (non-Javadoc)
	 * @see net.rim.device.api.ui.Screen#onUiEngineAttached(boolean)
	 */
	protected void onUiEngineAttached(boolean attached) {
		if (attached) {
			String[] names = new String[] {"alertID", "page"};
			String[] values = new String[] {_id, "0"};
			
			SoapContentProvider soap = new SoapContentProvider("GetAlertInfoById", names, values);
			
			try{
				Serviceworker worker = new Serviceworker(this, AgentController.getServer(), soap);
				new Thread(worker).start();
			} catch (Exception ex){
				ex.printStackTrace();
			}
		}
	}

	protected void onBP() {
		//JSONUtil json = new JSONUtil(this.result);
		String bpCode = this.result.optString("BP Code");
		if(bpCode != null && !bpCode.equals("")){
			UiApplication.getUiApplication().pushScreen(new BPInfoScreen(bpCode));
		}
	}
	
	protected void onReject() {
		if(_rejectDialog == null){
			Dialog dialog = new Dialog(Dialog.D_OK, "Reject Remarks", Dialog.D_OK, null, Field.USE_ALL_WIDTH);
			
			Manager mgr = new VerticalFieldManager(Manager.USE_ALL_WIDTH){
				protected void sublayout(int width, int height) {
					super.sublayout(width, height);
				}
				protected void paint(Graphics graphics) {
					graphics.setColor(0x00333333);
					super.paint(graphics);
				};
			};
			
			_rejectRemark = new SingleLineEditField(Field.USE_ALL_WIDTH);
			mgr.add(_rejectRemark);
			dialog.add(mgr);
			dialog.setDialogClosedListener(this);
			_rejectDialog = dialog;
		}
		
		_rejectDialog.show();
	}

	protected void onApprove() {
		if(_approveDialog == null){
			Dialog dialog = new Dialog(Dialog.D_OK, "Approve Remarks", Dialog.D_OK, null, Field.USE_ALL_WIDTH);
			Manager mgr = new VerticalFieldManager(Manager.USE_ALL_WIDTH){
				protected void sublayout(int width, int height) {
					super.sublayout(width, height);
				}
				protected void paint(Graphics graphics) {
					graphics.setColor(0x00333333);
					super.paint(graphics);
				};
			};
			
			_approveRemark = new SingleLineEditField(Field.USE_ALL_WIDTH);
			mgr.add(_approveRemark);
			dialog.add(mgr);
			dialog.setDialogClosedListener(this);
			_approveDialog = dialog;
		}
		
		_approveDialog.show();
	}

	public void onGetResult(Serviceworker worker) {
		if(worker.responseCode == 200){
			ResponseParserHelper help = new ResponseParserHelper(worker.responseMessage);
			this.result = (JSONObject)help.parse("GetAlertInfoByIdResult");
			
			UiApplication.getUiApplication().invokeLater(new Runnable(){
				public void run() {
					bind();
				}
			});
		}
	}

	private void bind() {
		JSONUtil json = new JSONUtil(this.result);
		JSONArray titleArray = json.getArray("KeyList");
		
		for(int i = 0; i < titleArray.length(); i++){
			String title = JSONUtil.getStringElementByIndexFromJSONArray(titleArray, i);
			String value = json.getString(title);
			boolean link = title.equals("BP Code") || title.equals("BP Name");
			ListGroupItemField item = new ListGroupItemField(title, value, link);
			if(link){
				item.setChangeListener(new FieldChangeListener(){
					public void fieldChanged(Field field, int context) {
						onBP();
					}
				});
			}
			
			manager.add(item);
		}
		
		int line = Integer.parseInt(json.getString("LineCount"));
		if(line > 0){
			manager.add(new ListGroupItemField("Line Detail", String.valueOf(line) + " " + "Rows", false));
			
			for(int j = 0; j < line; j++){
				String key = "Line" + String.valueOf(j);
				String value = json.getString(key);
				if(!value.equals("")){
					manager.add(new ListGroupItemField(String.valueOf(j + 1), value, false));
				}				
			}
		}
		String statusFlag = json.getString("Status");
		if(!statusFlag.equals("W")){
			String status = statusFlag.equals("Y") ? "Approved" : "Rejected";
			LabelField label = new LabelField(status, Field.FOCUSABLE);
			label.setFont(FontFactory.getFont(Font.BOLD, 6));
			label.setPadding(10, 0, 0, 10);
			
			getMainManager().insert(label, 0);
			label.setFocus();
			
			String approval = json.getString("ApprovalRemarks");
			LabelField remark = new LabelField(approval);
			remark.setFont(FontFactory.getFont(Font.PLAIN, 6));
			remark.setPadding(15, 0, 10, 10);
			getMainManager().insert(remark, 1);
		} else {
			HorizontalFieldManager btnMgr = new HorizontalFieldManager(USE_ALL_WIDTH);
			btnMgr.setPadding(10, 0, 10, 0);
			ButtonField btnApprove = new ButtonField("Approve", Field.FIELD_HCENTER);
			ButtonField btnReject = new ButtonField("Reject", Field.FIELD_HCENTER);
			
			btnApprove.setChangeListener(new FieldChangeListener(){
				public void fieldChanged(Field arg0, int arg1) {
					onApprove();
				}
			});
			
			btnReject.setChangeListener(new FieldChangeListener(){
				public void fieldChanged(Field arg0, int arg1) {
					onReject();
				}
			});
			
			btnMgr.add(btnApprove);
			btnMgr.add(btnReject);
			
			getMainManager().insert(btnMgr, 0);
			
			btnApprove.setFocus();
		}
	}

	public void dialogClosed(Dialog dialog, int arg1) {
		if(arg1 == Dialog.D_OK){
			if(dialog == _approveDialog){
				JSONUtil.putOpt(this.result, "Status", "Y");
				JSONUtil.putOpt(this.result, "ApprovalRemarks", _approveRemark.getText());
				_approveRemark.setText("");
			} else {
				JSONUtil.putOpt(this.result, "Status", "N");
				JSONUtil.putOpt(this.result, "ApprovalRemarks", _rejectRemark.getText());
				_rejectRemark.setText("");
			}
			
			manager.deleteAll();
			getMainManager().deleteAll();
			getMainManager().add(manager);
			
			bind();
		}		
	}

}
